package com.tc.itfarm.web.interceptor;

import com.tc.itfarm.api.annotation.FormToken;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wangdongdong on 2016/8/11.
 */
public class SessionTokenHandlerInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(SessionTokenHandlerInterceptor.class);

    /**
     * 请求处理之前调用
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("-------------------");
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            FormToken annotation = method.getMethodAnnotation(FormToken.class);
            if (annotation != null) {
                // 从session中取出比较
                String sToken = (String) request.getSession().getAttribute("stoken");
                String rToken = request.getParameter("rtoken");
                if (sToken != null && sToken.equals(rToken)) {
                    logger.error("数据已经失效");
                    throw new RuntimeException("数据已经失效");
                }
                String stoken = RandomStringUtils.randomAlphanumeric(32);
                request.getSession().setAttribute("stoken",stoken);
                request.setAttribute("formToken","<input type='hidden' name='rtoken' value='"+stoken+"'>");
            }
        }
        return true;
    }

    /**
     * Controller方法调用之后，界面渲染之前调用
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 渲染视图后执行，主要用于清理资源
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
